<script lang="ts" setup>
  import { ref } from 'vue';
  import { useFileDialog } from '@vueuse/core';
  import { importPlayerHoleScores } from '@/api/game';
  import { Notification } from '@arco-design/web-vue';

  const props = defineProps<{
    gameId: string;
  }>();

  const emit = defineEmits(['close', 'done']);

  const handleDownloadTpl = async () => {
    window.open('/templates/成绩导入模板.xlsx');
  };

  const { open, reset, onChange } = useFileDialog({
    accept: '.xlsx',
    multiple: false,
  });

  const uploading = ref(false);

  onChange(async (files) => {
    if (files && files.length === 1) {
      const { close } = Notification.info('正在导入，请稍候');
      const fd = new FormData();
      fd.append('file', files[0]);
      uploading.value = true;
      try {
        const res = await importPlayerHoleScores(props.gameId, fd);
        uploading.value = false;
        emit('done', res.data.data);
      } finally {
        close();
      }
    }
  });

  const beginUpload = () => {
    reset();
    open();
  };
</script>

<template>
  <a-modal
    title="导入逐洞成绩"
    :width="500"
    visible
    @cancel="emit('close', false)"
  >
    <a-button type="primary" @click="beginUpload">
      <template #icon><icon-upload /></template>
      上传成绩表
    </a-button>
    <div style="height: 20px"></div>
    <a-link @click="handleDownloadTpl"> <icon-download />下载模板 </a-link>
  </a-modal>
</template>
